package com.gwtsz.chart.output.utils;

import android.graphics.Canvas;
import android.graphics.Paint;
import android.graphics.Typeface;
import android.text.TextPaint;

/**
 * 画笔，用于在界面绘制各种控件，可设定所绘视图的间距和对齐方式等
 *
 */
public class UiTextPaint extends TextPaint {

	private AutoScaleTextUtil m_scaleTextUtil;
	private VAlign m_valign = VAlign.TOP;
	private float m_yoffset = 0.0f;
	private FontMetrics m_fontMetrics;
	
	public enum VAlign {
		TOP, CENTER, BOTTOM
	}

	public UiTextPaint() {
		super();
		init();
	}

	public UiTextPaint(int flags) {
		super(flags);
		init();
	}

	public UiTextPaint(Paint p) {
		super(p);
		init();
	}

	private void init() {
		m_fontMetrics = new FontMetrics();
		m_valign = VAlign.TOP;
	}

	public void setTextVAlign(VAlign align) {
		m_valign = align;

		getFontMetrics(m_fontMetrics);
		final FontMetrics fm = m_fontMetrics;

		switch (m_valign) {
		default:
		case TOP:
			m_yoffset = -fm.top;
			break;
		case CENTER:
			m_yoffset = -fm.top - ((-fm.top + fm.bottom) / 2);
			break;
		case BOTTOM:
			m_yoffset = -fm.bottom;
			break;
		}
	}

	public float getHeight() {
		return -m_fontMetrics.top + m_fontMetrics.bottom;
	}

	@Override
	public Typeface setTypeface(Typeface typeface) {
		Typeface oldTypeface = super.setTypeface(typeface);

//		setTextVAlign(m_valign);
		return oldTypeface;
	}

	public void draw(Canvas canvas, String text, float x, float y) {
		canvas.drawText(text, x, y + m_yoffset, this);
	}

	/**
	 * 根据给定坐标自动绘制控件显示指定text
	 * @param canvas
	 * @param text
	 * @param x
	 * @param y
	 * @param expectedWidth
	 * @return
	 */
	public float autoScaleDraw(Canvas canvas, String text, float x, float y,
			float expectedWidth) {
		final float textSize = getTextSize();
		final float textScaleX = getTextScaleX();
		float width = 0.0f;

		if (m_scaleTextUtil == null)
			m_scaleTextUtil = new AutoScaleTextUtil();

		m_scaleTextUtil.setMaxTextSize(textSize);
		m_scaleTextUtil.setTextScaleX(textScaleX);
		AutoScaleTextUtil.AutoScaledSize scaledSize = m_scaleTextUtil.rescaleText(text, this,
				expectedWidth);
		if (scaledSize == null) {
			width = measureText(text);
			canvas.drawText(text, x, y + m_yoffset, this);
		} else {
			width = scaledSize.mMeasuredWidth;
			setTextSize(scaledSize.mTextSize);
			setTextScaleX(scaledSize.mTextScaleX);
			setTextVAlign(m_valign);
			canvas.drawText(text, x, y + m_yoffset, this);
		}

		setTextSize(textSize);
		setTextScaleX(textScaleX);
		setTextVAlign(m_valign);
		return width;
	}
}
